const dbConfig = require('../database/dbconfig')
var querystring = require('querystring');

// 解析消息，获取传递的参数
function parseReq(req) {
    str = JSON.stringify(req.body)
    let postinfo = {}
    if (str.length === 2) {
        // 使用post工具测试接口时传递的值在query里
        postinfo = req.query;
    } else {
        //  从前端跨域post的时候数据放在body里，面不是放在query里，不知道为什么
        str1 = eval(str.match("\{(.*)\:\"\"\}")[1])
        postinfo = JSON.parse(str1)
    }

    // str = JSON.stringify(req.body)
    // str1 = eval(str.match("\{(.*)\:\"\"\}")[1])
    // postinfo = JSON.parse(str1)
    return postinfo
}

getAlarmHis = (req, res) => {
    if (req.body.username === undefined) {
        var postinfo = req.query;
    } else {
        var postinfo = req.body;
    }

    let sql = "select * from alarmrecord ";
    // add condition if request
    if (postinfo.startdate || postinfo.enddate || postinfo.name || postinfo.source || postinfo.status || postinfo.handleby || postinfo.progress) {
        let wherestr = " where "
        let conditionStr = ""
        let andStr

        function putAnd() {
            if (!conditionStr) {
                andStr = ""
            } else {
                andStr = " and "
            }
        };
        if (postinfo.name) {
            putAnd();
            conditionStr = conditionStr + andStr + " name = " + "\'" + postinfo.name + "\'"
        }
        if (postinfo.enddate) {
            putAnd();
            conditionStr = conditionStr + andStr + " GenTime <= " + "\'" + postinfo.enddate + "\'"
        }
        if (postinfo.startdate) {
            putAnd();
            conditionStr = conditionStr + andStr + " GenTime >= " + "\'" + postinfo.startdate + "\'"
        }
        if (postinfo.source) {
            putAnd();
            conditionStr = conditionStr + andStr + " source = " + "\'" + postinfo.source + "\'"
        }
        if (postinfo.status) {
            putAnd();
            conditionStr = conditionStr + andStr + " status = " + "\'" + postinfo.status + "\'"
        }
        if (postinfo.handleby) {
            putAnd();
            conditionStr = conditionStr + andStr + " handleby = " + "\'" + postinfo.handleby + "\'"
        }
        if (postinfo.progress) {
            putAnd();
            conditionStr = conditionStr + andStr + " progress like " + "\'%" + postinfo.progress + "%\'"
        }
        sql = sql + wherestr + conditionStr
        console.log(sql)

    }
    let sqlArr = [];
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    let callBack = (err, sqlResult) => {
        if (err) {
            res.send({
                'message': 'add new record failed',
                'code': 100,
                'error': 'sql execute failed',
                'data': sqlResult,
            })
        } else {
            res.send({
                'message': 'add new record success',
                'code': 200,
                'error': 'sql execute failed',
                'data': sqlResult,
            })
        }
    }
    dbConfig.sqlConnect(sql, sqlArr, callBack)
}



addAlarmRecord = (req, res) => {

    let postinfo = parseReq(req);
    if (!postinfo.name) {
        console.log("name can not null")
        res.send({
            'message': 'name can not null',
            'code': 102,
            'error': 'name can not null',
        })
    }
    if (!postinfo.genTime) {
        console.log("no genTime recieved, use currenttime")
        let now = new Date();
        let day = ("0" + now.getDate()).slice(-2);
        let month = ("0" + (now.getMonth() + 1)).slice(-2);
        let hours = ("0" + (now.getHours() + 1)).slice(-2);
        let minutes = ("0" + (now.getMinutes() + 1)).slice(-2);
        let seconds = ("0" + (now.getSeconds() + 1)).slice(-2);
        let time = now.getHours
        let nwodate = now.getFullYear() + "/" + (month) + "/" + (day) + " " + hours + ":" + minutes + ":" + seconds;
        postinfo.genTime = nwodate
    }
    if (!postinfo.source) {
        postinfo.source = "Others"
    }
    if (!postinfo.status) {
        postinfo.status = "Open"
    }
    if (!postinfo.progress) {
        postinfo.progress = ""
    }
    if (!postinfo.handleby) {
        postinfo.handleby = ""
    }
    if (!postinfo.record) {
        postinfo.record = ""
    }
    let sql = "INSERT INTO `alarmrecord`( `name`, `gentime`, `source`, `status`, `handleby`, `progress`, `record`)  VALUES(? , ? , ? , ? , ? , ? , ? ) ";
    // console.log(sql)

    let sqlArr = [postinfo.name, postinfo.genTime, postinfo.source, postinfo.status, postinfo.progress, postinfo.handleby, postinfo.record];
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    let callBack = (err, sqlResult) => {
        if (err) {
            res.send({
                'message': 'add new record failed',
                'code': 100,
                'error': 'sql execute failed',
                'list': sqlResult,
            })
        } else {
            res.send({
                'message': 'add new record success',
                'code': 200,
                'error': 'sql execute success',
                'list': sqlResult,
            })
        }
    }
    dbConfig.sqlConnect(sql, sqlArr, callBack)
}


getAlarmCfg = (req, res) => {
    let { id } = req.query;
    let sql = "select * from user where userid=? ";
    let sqlArr = [id];
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    let callBack = (err, sqlResult) => {
        if (err) {
            console.log('sql execute failed, ErrorInfo: ')
            res.send({
                'stauts': 'failed',
            })
        } else {
            // console.log(sqlResult);
            res.send({
                'list': sqlResult
            })
        }
    }
    dbConfig.sqlConnect(sql, sqlArr, callBack)
}


updateAlarmRecord = (req, res) => {


    let postinfo = parseReq(req)
    let sqlArr = [];
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    let sql = "update alarmrecord set ";
    // add condition if request
    if (!postinfo.alarmid) {
        res.send({
            'error': 'alarmID not in the post parameter',
        })
        return 0
    }

    if (postinfo.startdate || postinfo.enddate || postinfo.name || postinfo.source || postinfo.status || postinfo.handleby || postinfo.progress) {
        let wherestr = " where alarmid = " + postinfo.alarmid
        let conditionStr = ""
        let andStr

        function putAnd() {
            if (!conditionStr) {
                andStr = ""
            } else {
                andStr = " , "
            }
        };
        if (postinfo.name) {
            putAnd();
            conditionStr = conditionStr + andStr + " name = " + "\'" + postinfo.name + "\'"
        }
        if (postinfo.source) {
            putAnd();
            conditionStr = conditionStr + andStr + " source = " + "\'" + postinfo.source + "\'"
        }
        if (postinfo.status) {
            putAnd();
            conditionStr = conditionStr + andStr + " status = " + "\'" + postinfo.status + "\'"
        }
        if (postinfo.handleby) {
            putAnd();
            conditionStr = conditionStr + andStr + " handleby = " + "\'" + postinfo.handleby + "\'"
        }
        if (postinfo.progress) {
            putAnd();
            conditionStr = conditionStr + andStr + " progress = " + "\'" + postinfo.progress + "\'"
        }
        if (postinfo.record) {
            putAnd();
            conditionStr = conditionStr + andStr + " record = " + "\'" + postinfo.record + "\'"
        }
        sql = sql + conditionStr + wherestr
        console.log(sql)

    }

    let callBack = (err, sqlResult) => {
        if (err) {
            res.send({
                'message': 'update record failed',
                'code': 100,
                'list': sqlResult,
            })
        } else {
            if (sqlResult.affectedRows === 0) {
                console.log('no record be change :>> ');
                res.send({
                    'message': 'no record be change,alarmid not exist',
                    'code': 101,
                    'list': sqlResult,
                })
            } else {
                res.send({
                    'message': 'update record success',
                    'code': 200,
                    'list': sqlResult,
                })
            }

        }
    }
    dbConfig.sqlConnect(sql, sqlArr, callBack)
}


removeAlarmRecord = (req, res) => {
    let postinfo = parseReq(req)
    let sqlArr = [];
    res.header('Access-Control-Allow-Origin', "*");
    res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE');
    res.header('Access-Control-Allow-Headers', 'Content-Type');
    let sql = "delete from alarmrecord where alarmid= ";
    // add condition if request
    if (!postinfo.alarmid) {
        console.log('alarmid not exist')
        res.send({
            'error': 'alarmid not in post info',
        })
        return 0
    } else {

        sql = sql + postinfo.alarmid;
        console.log(sql);

    }
    let callBack = (err, sqlResult) => {

        if (sqlResult.affectedRows === 0) {
            res.send({
                'message': 'no record be removed,alarmid not exist',
                'code': 101,
                'list': sqlResult,
            })
        } else {
            res.send({
                'message': 'remove record success',
                'code': 200,
                'list': sqlResult,
            })
        }

    }
    dbConfig.sqlConnect(sql, sqlArr, callBack)
}


module.exports = {

    getAlarmHis,
    getAlarmCfg,
    addAlarmRecord,
    updateAlarmRecord,
    removeAlarmRecord,
}